import { ElMessage } from 'element-plus'
import { tokenStore } from '@/store/token'
import { loadingStore } from '@/store/loading'
import { AxiosInstance } from 'axios'
import { Request } from './request'

//是否有加载特效
const isLoading = true
//调用队列
const queue = [] as string[]
let timerId = {} as NodeJS.Timeout
const errorMap: { [key: string]: string } = {
  '400': '访问数据错误',
  '401': '登录凭证过期',
  '404': '请求的资源找不到',
  '500': '服务器内部错误',
  '501': '登录失败',
  '502': '登录凭证过期',
  '503': '服务器正忙，请稍后再试',
  '504': '非法请求',
  '505': '请求出错',
  '506': '未经授权',
  '507': '禁止访问',
  '508': '请求的资源找不到',
  '509': '中间件调用失败',
  '510': '请求过于频繁'
}

const instance = new Request({
  baseUrl: '/api',
  timeout: 60000
})

//请求拦截器
instance.interceptors.request = (instance: AxiosInstance) => {
  instance.interceptors.request.use(
    config => {
      if (isLoading) {
        //清除定时器
        timerId && clearTimeout(timerId)
        queue.length === 0 && loadingStore().openLoading()
        queue.push('request')
      }
      config.headers = config.headers || {}
      const userstore = tokenStore()
      // 请求头设置
      if (userstore.token) {
        config.headers.WXToken = userstore.token
      } else {
        userstore.logOff()
      }
      if ((!config.headers.permission || config.headers.permission === '') && config.url) {
        config.headers.permission = String(config.url).replace('/api/', '').replaceAll('/', ':')
      }
      return config
    },
    err => Promise.reject(err)
  )
}

//响应拦截器
instance.interceptors.response = (instance: AxiosInstance) => {
  instance.interceptors.response.use(
    (res: any) => {
      if (isLoading) {
        queue.pop()
        queue.length === 0 && queue.push('request')
        timerId = setTimeout(() => {
          queue.pop()
          queue.length === 0 && loadingStore().closeLoading()
          clearTimeout(timerId)
        }, 1)
      }
      if (res.data.code !== 200) {
        return errorDetail(res.data.code, res.data.msg)
      }
      res.data = res.data.data
      return res
    },
    (err: any) => {
      queue.pop()
      clearTimeout(timerId)
      loadingStore().closeLoading()
      const code = err.response.data.status | err.response.data.code
      return errorDetail(code, err.msg)
    }
  )
}
/**
 * 获取错误信息
 * @param code
 * @param msg
 * @returns
 */
const errorDetail = (code: number, msg: string) => {
  if (!code) {
    code = 503
  }
  if (code === 502) {
    tokenStore().logOff()
    return
  }
  let errMsg = errorMap[code + '']
  if (!errMsg) {
    errMsg = '未知错误'
  }
  ElMessage({
    message: msg || errMsg,
    type: 'error'
  })
  return Promise.reject(new Error(errMsg))
}

export default instance
